/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.colswe.solestac.view;

import java.awt.Color;
import java.util.List;
import javax.swing.JOptionPane;
import org.colswe.solestac.VO.StudentVO;
import org.colswe.solestac.control.StudentControl;

/**
 *
 * @author solid
 */
public class NewStudent extends javax.swing.JFrame {

    /**
     * Creates new form newUser
     *
     */
    private StudentVO student;
    private NewRequest request;
    private StudentControl studentControl;

    public NewStudent(NewRequest request, String doc) {
        studentControl = new StudentControl();
        this.request = request;
        initComponents();      
        setVisible(true);
        documentTF.setText(doc);
        documentTF.setEditable(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        newUserPanel = new javax.swing.JPanel();
        createButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        nameLbl = new javax.swing.JLabel();
        lastNamesLbl = new javax.swing.JLabel();
        codeLbl = new javax.swing.JLabel();
        documentLbl = new javax.swing.JLabel();
        programLbl = new javax.swing.JLabel();
        nameTF = new javax.swing.JTextField();
        lastNameTF = new javax.swing.JTextField();
        documentTF = new javax.swing.JTextField();
        codeTF = new javax.swing.JTextField();
        List<String> programs = studentControl.getAllPrograms();
        programCB = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nuevo Usuario");
        setMinimumSize(new java.awt.Dimension(100, 100));
        setPreferredSize(new java.awt.Dimension(730, 500));

        newUserPanel.setBackground(new java.awt.Color(255, 255, 255));
        newUserPanel.setPreferredSize(new java.awt.Dimension(572, 400));

        createButton.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        createButton.setText("Crear");
        createButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createButtonActionPerformed(evt);
            }
        });

        cancelButton.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        cancelButton.setText("Cancelar");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        nameLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        nameLbl.setText("Nombres");

        lastNamesLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        lastNamesLbl.setText("Apellidos");

        codeLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        codeLbl.setText("Código");

        documentLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        documentLbl.setText("Cédula");

        programLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        programLbl.setText("Programa Curricular");

        nameTF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameTFActionPerformed(evt);
            }
        });

        programCB.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        programCB.setModel(new javax.swing.DefaultComboBoxModel(programs.toArray()));

        javax.swing.GroupLayout newUserPanelLayout = new javax.swing.GroupLayout(newUserPanel);
        newUserPanel.setLayout(newUserPanelLayout);
        newUserPanelLayout.setHorizontalGroup(
            newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(newUserPanelLayout.createSequentialGroup()
                .addGap(84, 84, 84)
                .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(newUserPanelLayout.createSequentialGroup()
                        .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nameLbl)
                            .addComponent(lastNamesLbl)
                            .addComponent(documentLbl)
                            .addComponent(codeLbl))
                        .addGap(41, 41, 41)
                        .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(nameTF, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                            .addComponent(lastNameTF)
                            .addComponent(documentTF)
                            .addComponent(codeTF)))
                    .addGroup(newUserPanelLayout.createSequentialGroup()
                        .addComponent(programLbl)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(newUserPanelLayout.createSequentialGroup()
                                .addComponent(createButton, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(programCB, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(241, Short.MAX_VALUE))
        );
        newUserPanelLayout.setVerticalGroup(
            newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, newUserPanelLayout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameLbl)
                    .addComponent(nameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lastNamesLbl)
                    .addComponent(lastNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(documentLbl)
                    .addComponent(documentTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(codeLbl)
                    .addComponent(codeTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(49, 49, 49)
                .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(programCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(programLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(48, 48, 48)
                .addGroup(newUserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(createButton)
                    .addComponent(cancelButton))
                .addGap(122, 122, 122))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(newUserPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 730, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(newUserPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cleanTF(){
        nameTF.setBackground(Color.white);
        lastNameTF.setBackground(Color.white);
        documentTF.setBackground(Color.white);
        codeTF.setBackground(Color.white);
    }

    private void nameTFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameTFActionPerformed
    }//GEN-LAST:event_nameTFActionPerformed

    private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createButtonActionPerformed
        cleanTF();
        student = new StudentVO();
        student.setDocument(documentTF.getText());
        student.setName(nameTF.getText());
        student.setLastName(lastNameTF.getText());
        student.setCode(codeTF.getText());
        student.setProgram(programCB.getSelectedItem().toString());

        int result = studentControl.registerStudent(student);

        if (result == 0) {
            JOptionPane.showMessageDialog(this, "El estudiante ha sido creado ",
                    "Transacción exitosa", JOptionPane.INFORMATION_MESSAGE);
            request.setStudent(student);
            setVisible(false);
            dispose();
            request.getPrincipal().toFront();

        } else if (result == -1) {
            JOptionPane.showMessageDialog(this, "El valor ingresado no es numérico", "Cédula inválida", JOptionPane.INFORMATION_MESSAGE);
            documentTF.setBackground(new Color(255,102,102));
       
        } else if (result == -2) {
            JOptionPane.showMessageDialog(this, "El valor ingresado no está entre el rango de límites;"
                    + "La cédula debe contener entre 6 y 12 dígitos", "Cédula inválida", JOptionPane.INFORMATION_MESSAGE);
            documentTF.setBackground(new Color(255,102,102));
        } else if (result == -3) {
            JOptionPane.showMessageDialog(this, "El estudiante ya existe en el sistema", "Usuario repetido", JOptionPane.INFORMATION_MESSAGE);
            documentTF.setBackground(new Color(255,102,102));
        } else if (result == -4) {
            
            JOptionPane.showMessageDialog(this, "El formato del nombre es incorrecto", "Nombre inválido", JOptionPane.INFORMATION_MESSAGE);
            nameTF.setBackground(new Color(255,102,102));            
        } else if (result == -5) {
            JOptionPane.showMessageDialog(this, "La longitud del nombre es incorrecta."
                    + "El nombre debe contener entre 2 y 45 letras", "Nombre inválido", JOptionPane.INFORMATION_MESSAGE);
            nameTF.setBackground(new Color(255,102,102));            
        } else if (result == -6) {
            JOptionPane.showMessageDialog(this, "El formato de los  apellidos es incorrecto", "Apellidos inválidos", JOptionPane.INFORMATION_MESSAGE);
            lastNameTF.setBackground(new Color(255,102,102));            
        } else if (result == -7) {
            JOptionPane.showMessageDialog(this, "La longitud de los apellidos es incorrecta", "Apellidos", JOptionPane.INFORMATION_MESSAGE);
            lastNameTF.setBackground(new Color(255,102,102));            
        } else if (result == -8) {
            JOptionPane.showMessageDialog(this, "El formato del código es incorrecto", "Código inválido", JOptionPane.INFORMATION_MESSAGE);
            codeTF.setBackground(new Color(255,102,102));            
        } else if (result == -9) {
            JOptionPane.showMessageDialog(this, "La longitud del código es incorrecta", "Código inválido", JOptionPane.INFORMATION_MESSAGE);
            codeTF.setBackground(new Color(255,102,102));            
        } else if (result == -10) {
            JOptionPane.showMessageDialog(this, "El programa curricular escogido no es válido", "Programa curricular inválido", JOptionPane.INFORMATION_MESSAGE);
        } else if (result == -11) {
            JOptionPane.showMessageDialog(this, "Ha ocurrido un error mientras se realizaba la "
                    + "transacción", "Error inseperado", JOptionPane.ERROR_MESSAGE);
        }


    }//GEN-LAST:event_createButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        request.setStudent(null);
        setVisible(false);
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel codeLbl;
    private javax.swing.JTextField codeTF;
    private javax.swing.JButton createButton;
    private javax.swing.JLabel documentLbl;
    private javax.swing.JTextField documentTF;
    private javax.swing.JTextField lastNameTF;
    private javax.swing.JLabel lastNamesLbl;
    private javax.swing.JLabel nameLbl;
    private javax.swing.JTextField nameTF;
    private javax.swing.JPanel newUserPanel;
    private javax.swing.JComboBox programCB;
    private javax.swing.JLabel programLbl;
    // End of variables declaration//GEN-END:variables
}
